package com.jn.erp.wechat.mp.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jn.erp.security.entity.SysUser;
import com.jn.erp.security.sysservice.SysUserService;
import com.jn.erp.wechat.common.api.entity.WxMpUser;
import com.jn.erp.wechat.common.api.service.WxMpUserService;
import com.jn.erp.wechat.mp.entity.ReceiveMessage;
import com.jn.erp.wechat.mp.utils.XMLUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <pre>
 *  监听服务号 消息
 * </pre>
 *
 * @author sunjiyong
 * @since 2024/11/26 14:31
 */
@Service
public class ReceiveEventsService {

    //小程序与服务号关联
    @Autowired
    private WxMpUserService wxMpUserService;

    @Autowired
    private SysUserService sysUserService;


    public ReceiveMessage events(String xml) {
        ReceiveMessage receiveMessage = XMLUtil.XMLTOModel(xml);
        System.out.println(receiveMessage.toString());
        ReceiveMessage reCell = new ReceiveMessage();
        reCell.setFromUserName(receiveMessage.getToUserName());
        reCell.setToUserName(receiveMessage.getFromUserName());

        reCell.setMsgType("text");
        reCell.setCreateTime(DateUtil.current() + "");
        reCell.setContent(null);

        //接收普通消息
        String content=receiveMessage.getContent();
        if(StrUtil.equals(receiveMessage.getMsgType(), "text")&&StrUtil.isNotBlank(content) &&StrUtil.startWith(content, "员工")){
            String phoneNumber=StrUtil.subSuf(content, 2);
            boolean isPhoneNumber = ReUtil.isMatch("^1[3-9]\\d{9}$", phoneNumber);
            if(!isPhoneNumber) {
                reCell.setContent("输入要绑定的手机号有误");
                return reCell;
            }
            QueryWrapper<SysUser> quser=new QueryWrapper<>();
            quser.eq("mobile", phoneNumber);
            quser.eq("state", "0");
            List<SysUser> list = sysUserService.list(quser);
            if(list.size()==0){
                reCell.setContent("要绑定的手机号未在该系统注册");
                return reCell;
            }
            SysUser sysUser = list.get(0);
            boolean re= wxMpUserService.updateBind(sysUser.getId(),sysUser.getMobile(),receiveMessage.getFromUserName());
            if (re) {
                reCell.setContent("员工通知功能已开通");
            } else {
                reCell.setContent("员工通知功能开通失败！请联系管理员");
            }
        }

        //接收事件推送
        if (StrUtil.equals(receiveMessage.getMsgType(), "event")) {
            //点击事件
            if (StrUtil.equals(receiveMessage.getEvent(), "CLICK")) {
                //查看开通状态
                if (StrUtil.equals(receiveMessage.getEventKey(), "isBind")) {
                    QueryWrapper<WxMpUser> qw=new QueryWrapper();
                    qw.eq("mpid", receiveMessage.getFromUserName());
                    List<WxMpUser> list = wxMpUserService.list(qw);
                    if(list.size()==0){
                        reCell.setContent("该微信账户下未开通消息功能");
                        return reCell;
                    }
                    StringBuffer stringBuffer=new StringBuffer();
                    //查询是否开通家长端
                    List<WxMpUser> student = list.stream().filter(u -> u.getBindType() == 1).collect(Collectors.toList());
                    if(student.size()>0){
                        stringBuffer.append("该微信账户已开通家长消息通知");
                    }
                    //查询是否开通员工端
                    List<String> staff = list.stream().filter(u -> u.getBindType() == 2).map(WxMpUser::getMobile).collect(Collectors.toList());
                    if(staff.size()>0) {
                        if (stringBuffer.length() > 0) {
                            stringBuffer.append("\n");
                        }
                        stringBuffer.append("该微信账户已开通员工消息通知");
                        stringBuffer.append("\n绑定员工手机号：" + String.join(",", staff));
                    }
                    reCell.setContent(stringBuffer.toString());
                    return reCell;
                }
            }
            //扫码事件
            if (StrUtil.equals(receiveMessage.getEvent(), "SCAN")) {
                String key = receiveMessage.getEventKey();
                //判断是否为通知事件（notice_）
                boolean notice = StrUtil.startWith(key, "notice_");
                if (notice) {
                    String openid=StrUtil.subSuf(key, 7);
                    boolean re= wxMpUserService.updateBind(openid,receiveMessage.getFromUserName());
                    if (re) {
                        reCell.setContent("通知功能已开通");
                    } else {
                        reCell.setContent("通知功能开通失败！请联系管理员");
                    }
                }
            }
            //关注事件
            if (StrUtil.equals(receiveMessage.getEvent(), "subscribe")) {
                String key = receiveMessage.getEventKey();
                //判断是否为关注通知事件（qrscene_notice_）
                boolean notice = StrUtil.startWith(key, "qrscene_notice_");
                if (notice) {
                    String openid=StrUtil.subSuf(key, 15);
                    boolean re= wxMpUserService.updateBind(openid,receiveMessage.getFromUserName());
                    if (re) {
                        reCell.setContent("通知功能已开通");
                    } else {
                        reCell.setContent("通知功能开通失败！请联系管理员");
                    }
                }else{
                    reCell.setContent("终于等到您，感谢您选择江南文化艺术服务系统陪你一起见证孩子的成长！绑定手机号，您可以上课提醒，提前获取；签到信息，及时收到；课堂表现，随时了解；请假申请，一键完成；机构优惠，从不错过！");
                }
            }
            //取消关注事件
            if (StrUtil.equals(receiveMessage.getEvent(), "unsubscribe")) {
                String openid=receiveMessage.getFromUserName();
                QueryWrapper<WxMpUser> qw=new QueryWrapper();
                qw.eq("mpid", openid);
                wxMpUserService.remove(qw);
            }
        }
        return reCell;
    }
}
